package com.example.nyf.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.nyf.common.AjaxResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LoginController {

    @RequestMapping(value={"login","/"})
    public ModelAndView login() {
        ModelAndView modelAndView =  new ModelAndView("login/index.html");

        return modelAndView;
    }

    @PostMapping("/check_login")
    @ResponseBody
    public AjaxResult checkLogin(@RequestBody String post) {
        JSONObject jsonObject = JSON.parseObject(post);
        String userName = jsonObject.getString("user_name");
        String passWord = jsonObject.getString("password");

        var token = new UsernamePasswordToken(userName, passWord);
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);

//            Session xx = subject.getSession();
//            xx.setAttribute("user", (String)subject.getPrincipal());
//
//            SecurityUtils.getSubject().getSession().setTimeout(30);
//            System.out.println(xx);

            subject.hasRole("登录");

        } catch (IncorrectCredentialsException e) {
            return AjaxResult.error("密码不正确");
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }

        return AjaxResult.success();
    }

    @RequestMapping("/login_out")
    public String loginOut(Model map) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "/login/index";
        //return "redirect: xx";
    }

}
